package cn.darkfire.web.Utils;

import cn.darkfire.web.POJO.Status;
import cn.darkfire.web.POJO.User;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

public class DataUtils {
    private static final DataUtils instance = new DataUtils();
    private final HashMap<String,User> userData = new HashMap<>();

    public String isTrueData(User user){
        //传入用户,判断用户数据是否合规
        if(user.getAge()<=0||user.getAge()>=120){
           return Status.getInstance().setStatus(-1,"用户年龄输入错误");
        }else if(user.getName().length()<=0||user.getName().length()>6){
            return Status.getInstance().setStatus(-1,"用户昵称输入错误");
        }else if (user.getHobbys().length==0){
            return Status.getInstance().setStatus(-1,"用户爱好输入错误");
        }
        return Status.getInstance().setStatus(200,"格式校验成功");
    }

    public String addUser(User user){
        if(userData.containsKey(user.getName())){
            return Status.getInstance().setStatus(-1,"存在该用户");
        }else{
            userData.put(user.getName(),user);
            return Status.getInstance().setStatus(200,"存储用户"+user.getName()+"成功");
        }
    }

    public HashMap<String,User> getUsers(){
       return this.userData;
    }

    public static DataUtils getInstance() {
        return instance;
    }

    public String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest( plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }


}
